from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseForbidden
from django.template.loader import render_to_string
from django.template import RequestContext
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.views.generic.list_detail import object_list

from pypsqueak.group.models import *
from pypsqueak.group.forms import *
from pypsqueak.profile.forms import *
from pypsqueak.chrome.models import add_model_chrome, model_chrome_list_header
from pypsqueak.chrome.forms import ChromeBreadcrumbForm

def group_read( request, group_slug ):
	""" Return a single group """

	group = get_object_or_404(Group, slug=group_slug)
	assignments = group.assignment_set.all()

	group = add_model_chrome(group, request)
	profile = group.get_profile()
	members = Membership.objects.filter(group=group)

	if not group.permission(request.user,'select'):
		return HttpResponseForbidden()

	# Load breadcrumb
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(group.get_absolute_url(),group.title)


	return render_to_response( 'group/group_detail.html',
							locals(),
							context_instance=RequestContext(request) )


def group_list( request ):
	""" Return the list of groups """

	list = Group.objects.all()
	header = model_chrome_list_header('Group List',Group, request.user)

	return object_list( request,
		queryset=list,
		paginate_by=30,
		extra_context={'request': request, 'group_list_header':header})


@login_required
def group_insert( request ):
	""" Insert a single group """

	if not Group.insert_permission(request.user):
		return HttpResponseForbidden()

	if request.method == 'POST':
		form = GroupInsertForm(request.POST)
		if form.is_valid():
			new_group = form.save()
			membership = Membership( user=request.user, group=new_group )
			membership.save()
			request.user.message_set.create(message='Group created')
			return HttpResponseRedirect( new_group.get_absolute_url() )
	else:
		form = GroupInsertForm()

	return render_to_response( 'group/group_insert.html', locals(),
							context_instance=RequestContext(request) )


@login_required
def group_update( request, group_slug ):
	""" Update a group """

	group = get_object_or_404(Group, slug=group_slug)
	profile = group.get_profile()

	if not group.permission(request.user,'update'):
		return HttpResponseForbidden()

	forms = ComboForm()

	forms.add_form(GroupUpdateForm, instances=group, request=request)
	forms.add_form(ProfileUpdateForm, instances=profile, request=request)
	forms.add_form(AssignmentInlineUpdateForm,
		instances=group.assignment_set.all(),
		request=request)
	forms.add_form(MembershipInlineUpdateForm,
		instances=Membership.objects.filter(group=group),
		request=request)

	if request.method == 'POST':
		if not group.permission(request.user,'update'):
			return HttpResponseForbidden()
		if forms.is_valid():
			forms.save()
			request.user.message_set.create(message='Group updated')
			return HttpResponseRedirect(group.get_absolute_url())

	# Add after save, as we only save the add forms via ajax.
	forms.add_dependent_form(AssignmentAjaxInsertForm, group)
	forms.add_dependent_form(MembershipAjaxInsertForm, group)

	# Load breadcrumb
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(group.get_absolute_url(),group.title)
	breadcrumb.append(group.get_absolute_url(),"Update")

	return render_to_response( 'group/group_update.html', locals(),
							context_instance=RequestContext(request) )


@login_required
def group_delete( request, group_slug ):
	""" Delete an assignment """

	group = get_object_or_404(Group, slug=group_slug)
	profile = group.get_profile()

	if not group.permission(request.user,'delete'):
		return HttpResponseForbidden()

	if request.method == "POST":
		group.delete()
		request.user.message_set.create(message='Group deleted')
		return HttpResponseRedirect( '/group/' )
	else:
		form = GroupDeleteForm(instance=group)

	# Load breadcrumb
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(group.get_absolute_url(),group.title)
	breadcrumb.append(group.get_absolute_url(),"Delete")

	return render_to_response( 'group/group_confirm_delete.html', locals(),
							context_instance=RequestContext(request) )


# Assignments.

def assignment_read( request, assignment_id ):
	""" Return a single assignment """

	assignment = get_object_or_404(Assignment, id=assignment_id)
	assignment = add_model_chrome(assignment, request)
	group = assignment.group
	profile = group.get_profile()

	if not group.permission(request.user,'select'):
		return HttpResponseForbidden()

	# Load breadcrumb
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(group.get_absolute_url(),group.title)
	breadcrumb.append(assignment.get_absolute_url(), assignment.title)

	return render_to_response( 'group/assignment_detail.html', locals(),
							context_instance=RequestContext(request) )


@login_required
def assignment_insert( request ):
	""" Insert a single assignment """

	if not Assignment.insert_permission(request.user):
		return HttpResponseForbidden()

	if request.method == 'POST':
		if request.is_ajax():
			form = AssignmentAjaxInsertForm(request.POST)
		else:
			form = AssignmentInsertForm(request.POST)

		if form.is_valid():
			assignment = form.save(commit=False)

			# Verify that the user has rights to the *group*
			if not assignment.group.permission(request.user,'update'):
				return HttpResponseForbidden()
			else:
				assignment.save()
				form.save_m2m()

			if request.is_ajax():
				form = AssignmentInlineUpdateForm(instance=assignment)
				return HttpResponse( form.as_template() )
			else:
				request.user.message_set.create(message='Assignment created')
				return HttpResponseRedirect( assignment.get_absolute_url() )
		else:
			if request.is_ajax():
				return HttpResponse( form.errors.as_text() )

	else:
		# Look for a default group in the parameters.
		group = request.GET.get("pk",-1)

		if group == -1:
			form = AssignmentInsertForm()
		else:
			# Verify that the user has rights to the *group*
			group = Group.objects.filter(pk=group)[0]
			profile = group.get_profile()
			if not group.permission(request.user,'update'):
				return HttpResponseForbidden()

			form = AssignmentGroupInsertForm(group=group.pk)

			# Load breadcrumb
			breadcrumb = ChromeBreadcrumbForm()
			breadcrumb.append(group.get_absolute_url(),group.title)


	return render_to_response( 'group/assignment_insert.html', locals(),
							context_instance=RequestContext(request) )


@login_required
def assignment_update( request, assignment_id ):
	""" Update an assignment """

	assignment = get_object_or_404(Assignment, id=assignment_id)
	group = assignment.group
	profile = group.get_profile()

	if not assignment.permission(request.user,'update'):
		return HttpResponseForbidden()

	if request.method == 'POST':
		form = AssignmentUpdateForm(request.POST, instance=assignment)
		if form.is_valid():
			a = form.save()
			request.user.message_set.create(message='Assignment updated')
			return HttpResponseRedirect( a.get_absolute_url() )
	else:
		form = AssignmentUpdateForm( instance=assignment)

	# Load breadcrumb
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(group.get_absolute_url(),group.title)
	breadcrumb.append(assignment.get_absolute_url(), assignment.title)
	breadcrumb.append(assignment.get_absolute_url(), 'Update')


	return render_to_response( 'group/assignment_update.html', locals(),
							context_instance=RequestContext(request) )


@login_required
def assignment_delete( request, assignment_id ):
	""" Delete an assignment """

	assignment = get_object_or_404(Assignment, id=assignment_id)
	group = assignment.group
	profile = group.get_profile()

	if not assignment.permission(request.user,'delete'):
		return HttpResponseForbidden()

	if request.method == "POST":
		assignment.delete()
		request.user.message_set.create(message='Assignment deleted')
		return HttpResponseRedirect( group.get_absolute_url() )
	else:
		form = AssignmentDeleteForm(instance=assignment)

	# Load breadcrumb
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(group.get_absolute_url(),group.title)
	breadcrumb.append(assignment.get_absolute_url(), assignment.title)
	breadcrumb.append(assignment.get_absolute_url(), 'Delete')

	return render_to_response( 'group/assignment_confirm_delete.html', locals(),
							context_instance=RequestContext(request) )


@login_required
def membership_insert( request ):
	""" Insert a single membership thru AJAX """

	if not Membership.insert_permission(request.user):
		return HttpResponseForbidden()

	if request.method == 'POST':
		form = MembershipAjaxInsertForm(request.POST)

		if form.is_valid():
			m = form.save(commit=False)

			# Verify that the user has rights to the *group*
			if not m.group.permission(request.user,'update'):
				return HttpResponseForbidden()
			else:
				m.save()
				form.save_m2m()

			form = MembershipInlineUpdateForm(instance=m)
			return HttpResponse( form.as_template() )
		else:
			return HttpResponse( form.errors.as_text() )
	else:
		# Browsing not allowed.
		return Http404()
